package com.nineclock.document.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.document.dto.DocFileDto;
import com.nineclock.document.dto.DocFileHistoryDto;
import com.nineclock.document.dto.DocFolderDto;
import com.nineclock.document.dto.DocumentDto;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.mapper.DocFileHistoryMapper;
import com.nineclock.document.mapper.DocFileMapper;
import com.nineclock.document.mapper.DocFolderMapper;
import com.nineclock.document.pojo.DocCollaborations;
import com.nineclock.document.pojo.DocFile;
import com.nineclock.document.pojo.DocFileHistory;
import com.nineclock.document.pojo.DocFolder;
import com.nineclock.document.service.DocumentService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class DocumentServiceImpl implements DocumentService {
    @Autowired
    SysUserFeign sysUserFeign;
    @Autowired
    DocCollaborationsMapper docCollaborationsMapper;
    @Autowired
    DocFileMapper docFileMapper;
    @Autowired
    private DocFileHistoryMapper docFileHistoryMapper;
    @Autowired
    DocFolderMapper docFolderMapper;

    /**
     * @description: 分页查询文件列表
     * @param: page
     * pageSize
     * keyword
     * @return: com.nineclock.common.entity.PageResult<com.nineclock.document.dto.DocFileDto>
     * @author 菜鸟
     * @date: 2021/7/22
     */
    @Override
    public PageResult<DocFileDto> PagingFile(Integer page, Integer pageSize, String keyword) {
        if (page == null || pageSize == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //创建分页条件
        Page<DocFile> filePage = new Page<>(page, pageSize);
        //查询文件列表
        LambdaQueryWrapper<DocFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        if (StrUtil.isNotEmpty(keyword)) {
            wrapper.like(DocFile::getName, keyword);
        }
        filePage = docFileMapper.selectPage(filePage, wrapper);
        //封装页面展示结果
        List<DocFile> records = filePage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            //结果转换
            List<DocFileDto> docFileDtos = BeanHelper.copyWithCollection(records, DocFileDto.class);
            for (DocFileDto docFileDto : docFileDtos) {
                //获取员工姓名并封装
                SysCompanyUserDTO companyUserDTO = sysUserFeign.queryCompanyUserById(docFileDto.getCreateUserId()).getData();
                docFileDto.setCreator(companyUserDTO);
                //查询协作者list
                List<SysCompanyUserDTO> list = new ArrayList<>();
                LambdaQueryWrapper<DocCollaborations> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DocCollaborations::getFileId, docFileDto.getId());
                List<DocCollaborations> docCollaborations = docCollaborationsMapper.selectList(queryWrapper);
                for (DocCollaborations docCollaboration : docCollaborations) {
                    SysCompanyUserDTO sysCompanyUserDTO = sysUserFeign.queryCompanyUserById(docCollaboration.getCollaborationId()).getData();
                    list.add(sysCompanyUserDTO);
                }
                //封装协作者信息
                docFileDto.setCollaborations(list);
            }
            PageResult<DocFileDto> pageResult = new PageResult(filePage.getTotal(), filePage.getPages(), docFileDtos);
            return pageResult;
        }
        return null;
    }

    /**
     * @description: 根据文件id修改文件状态
     * @param: field
     * status
     * @return: void
     * @author 菜鸟
     * @date: 2021/7/22
     */
    @Override
    public void fieldStatus(Long field, Short status) {
        //健壮性判断
        if (field == null || status == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //根据id查询 对象(从数据库)
        DocFile docFile = docFileMapper.selectById(field);
        if (docFile == null) {
            throw new NcException(ResponseEnum.FILE_NOT_FOUND);
        }
        //更新数据
        docFile.setStatus(status);
        //更新数据库
        docFileMapper.updateById(docFile);
    }


    /**
     * 根据文档id查询文档历史记录
     *
     * @param fileId
     * @return
     */
    @Override
    public List<DocFileHistoryDto> queryDocHistory(String fileId) {
        if (StrUtil.isEmpty(fileId)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        LambdaQueryWrapper<DocFileHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocFileHistory::getFileId, fileId);

        List<DocFileHistory> docFileHistories = docFileHistoryMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(docFileHistories)) {
            List<DocFileHistoryDto> docFileHistoryDtos = BeanHelper.copyWithCollection(docFileHistories, DocFileHistoryDto.class);

            for (DocFileHistoryDto docFileHistoryDto : docFileHistoryDtos) {
                SysCompanyUserDTO data = sysUserFeign.queryCompanyUserById(docFileHistoryDto.getOperateUserId()).getData();
                if (data != null) {
                    docFileHistoryDto.setUserName(data.getUserName());
                }
                return docFileHistoryDtos;
            }
        }
        return null;
    }

    /**
     * 查询文档里面所有的文件和文件夹
     *
     * @return
     */
    @Override
    public DocumentDto selectDepartment(Long parentId) {
        ArrayList<DocFileDto> commentList = new ArrayList<>();
        DocumentDto documentDto = new DocumentDto();
        Long companyId = CurrentUserHolder.get().getCompanyId();
        Long userId = CurrentUserHolder.get().getId();
        if (parentId == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        LambdaQueryWrapper<DocFolder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFolder::getParentId, parentId);
        wrapper.eq(DocFolder::getCompanyId, companyId);
        //wrapper.eq(DocFolder::getCreateUserId, userId);
        //查询所有文件夹
        List<DocFolder> docFolders = docFolderMapper.selectList(wrapper);
        if (!docFolders.isEmpty()) {
            //查询公有的
            LambdaQueryWrapper<DocFile> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DocFile::getCompanyId, companyId);
            wrapper1.eq(DocFile::getFolderId, docFolders.get(0).getParentId());
            wrapper1.in(DocFile::getPermission, 1, 0);
            //查询该文件下面所有的公共子文件
            List<DocFile> PublicFileList = docFileMapper.selectList(wrapper1);
            if (!PublicFileList.isEmpty()) {

                List<DocFileDto> docFileDtos = BeanHelper.copyWithCollection(PublicFileList, DocFileDto.class);
                //添加公共的
                commentList.addAll(docFileDtos);
                //documentDto.setFiles(docFileDtos);
            }
            LambdaQueryWrapper<DocFile> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(DocFile::getCompanyId, companyId);
            wrapper2.eq(DocFile::getFolderId, docFolders.get(0).getParentId());
            wrapper2.eq(DocFile::getPermission, 2);
            //私有文件
            List<DocFile> privateFileList = docFileMapper.selectList(wrapper2);
            List<DocFileDto> preFileDtos = BeanHelper.copyWithCollection(privateFileList, DocFileDto.class);
            if (!privateFileList.isEmpty()) {
                for (DocFileDto docFile : preFileDtos) {
                    //如果该私有文件的创建者id和当前的用户一样 就展示 加入集合
                    if (docFile.getCreateUserId().equals(userId)) {
                        commentList.add(docFile);
                    }
                    DocFile file = docFileMapper.queryCollaboration(docFile.getId(), userId);
                    if (file != null) {
                        DocFileDto docFileDto = BeanHelper.copyProperties(file, DocFileDto.class);
                        commentList.add(docFileDto);
                    }
                }
            }
        }

        List<DocFolderDto> docFolderDtos = BeanHelper.copyWithCollection(docFolders, DocFolderDto.class);
        documentDto.setFolders(docFolderDtos);
        documentDto.setFiles(commentList);
        return documentDto;
    }

    /**
     * @description: 文件创建
     * @param: docFileDto
     * @return: void
     * @author 菜鸟
     * @date: 2021/7/22
     */

    @Override
    public void insertFile(DocFileDto docFileDto) {

        //健壮性的判断传的参数是否存在
        if (docFileDto == null || docFileDto.getFolderId() == null) {
            throw new NcException(ResponseEnum.DELETE_OPERATION_FAIL);
        }

        DocFile docFile = new DocFile();

        docFile.setFolderId(docFileDto.getFolderId());
        docFile.setName(docFileDto.getName());
        docFile.setFilePath(docFileDto.getFilePath());

        //获取文件内容大小
        int length = docFileDto.getContent().getBytes().length;
        docFile.setFileSize(length + "");//文件大小

        docFile.setStatus((short) 1);
        docFile.setContent(docFileDto.getContent());
        docFile.setPermission((short) 1);
        docFile.setCompanyId(CurrentUserHolder.get().getCompanyId());
        docFile.setCreateUserId(CurrentUserHolder.get().getCompanyUserId());        //创建人id
        docFile.setCreateTime(new Date());


        docFileMapper.insert(docFile);


        //历史表
        DocFileHistory docFileHistory = BeanHelper.copyProperties(docFileDto, DocFileHistory.class);
        docFileHistory.setFileId(docFileDto.getFolderId());
        docFileHistory.setFileName(docFileDto.getName());
        docFileHistory.setOperateUserId(CurrentUserHolder.get().getCompanyUserId());
        docFileHistory.setOperateTime(new Date());
        docFileHistory.setIsCreate((short) 1);

        docFileHistoryMapper.insert(docFileHistory);

    }

    /**
     * @description: 文件夹创建
     * @param: docFolderDto
     * @return: void
     * @author 菜鸟
     * @date: 2021/7/22
     */
    @Override
    public void insertFolder(DocFolderDto docFolderDto) {

        //判断
        if (docFolderDto == null || docFolderDto.getParentId() == null) {
            throw new NcException(ResponseEnum.DELETE_OPERATION_FAIL);
        }

        DocFolder docFolder = BeanHelper.copyProperties(docFolderDto, DocFolder.class);

        docFolder.setCompanyId(CurrentUserHolder.get().getCompanyId());

        docFolder.setOrderNum(0);      //排序
        docFolder.setCreateUserId(CurrentUserHolder.get().getCompanyUserId());
        docFolder.setCreateTime(new Date());
        docFolder.setStatus((short) 1);

        docFolderMapper.insert(docFolder);

    }
}